//
//  StoresNearbyViewController.m
//  TerritoryShopkeeper
//
//  Created by 李小龙 on 2017/12/18.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "StoresNearbyViewController.h"
#import "StoresNearbyTableViewCell.h"
#import "StoresNearbyHomeModel.h"
#import "StoresNearbyGoodsViewController.h"
#import "MapViewController.h"

@interface StoresNearbyViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,BMKLocationServiceDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerBackView;

@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) BMKUserLocation *annotation;
@property (nonatomic, assign) CLLocationCoordinate2D selectLocation;

@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIView *clearMaskView;

@property (nonatomic, strong) NSMutableArray<StoresNearbyHomeModel *> *tableArray;

@end

@implementation StoresNearbyViewController
#pragma mark - Get
- (NSMutableArray<StoresNearbyHomeModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
        /*
         NSDictionary *dic = @{@"simg":@"http://pic.58pic.com/58pic/16/38/45/03i58PICDKP_1024.jpg",@"sname":@"境掌柜(北京丰台店)",@"sdistance":@"5.3"};
        for (NSInteger i = 0; i < 3; i++) {
            StoresNearbyHomeModel *model = [StoresNearbyHomeModel mj_objectWithKeyValues:dic];
            [_tableArray addObject:model];
        }
         */
    }
    return _tableArray;
}
- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setTitle:@"位置" forState:UIControlStateNormal];
        [_rightButton setTitleColor:[UIColor ThemeColor] forState:UIControlStateNormal];
        [_rightButton setImage:[UIImage imageNamed:@"position"] forState:UIControlStateNormal];
        [_rightButton.titleLabel setFont:TextPingFangFontSize(16)];
        [_rightButton addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [_rightButton setFrame:CGRectMake(0, 0, 100, 30)];
    }
    return _rightButton;
}
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        [_searchView.layer setCornerRadius:33.0/2.0];
        _searchView.clipsToBounds = YES;
        [_searchView setBackgroundColor:[UIColor grayF5Color]];
    }
    return _searchView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor grayF5Color]];
        _searchBar.placeholder = @"搜索你感兴趣的店铺";
        [_searchBar setSearchFieldBackgroundImage:[UIImage imageWithColor:[UIColor grayF5Color] size:CGSizeMake(ScreenWidth - 10*2, 33)] forState:UIControlStateNormal];
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.font = TextPingFangFontSize(14);
    }
    return _searchBar;
}
- (UIView *)clearMaskView {
    if (!_clearMaskView) {
        _clearMaskView = [[UIView alloc] init];
        _clearMaskView.backgroundColor = [UIColor clearColor];
        _clearMaskView.hidden = YES;
    }
    return _clearMaskView;
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createNavBar];
    [self createTableView];
    
    [self getLocation];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTintColor:[UIColor grayTextColor]];
}

#pragma mark - Action
- (void)createNavBar {
    self.navigationItem.title = @"附近门店";
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItem = right;
    
    [self.searchView addSubview:self.searchBar];
    self.searchView.frame = CGRectMake(10, 0, ScreenWidth - 10 * 2, 33);
    self.searchBar.frame = CGRectMake(0, 0, self.searchView.width, 33);
    [self.headerBackView addSubview:self.searchView];
    
    self.clearMaskView.frame = CGRectMake(0, 0, ScreenWidth, self.view.height - self.clearMaskView.top);
    [self.view addSubview:self.clearMaskView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewEndEditing)];
    [self.clearMaskView addGestureRecognizer:tapGesture];
    
}
- (void)rightBarButtonAction:(id)sender {
    __block typeof(self) blockSelf = self;
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.block = ^(CLLocationCoordinate2D coordinate) {
        NSLog(@"%f,%f",coordinate.latitude,coordinate.longitude);
        [blockSelf getLocationName:coordinate];
        
        blockSelf.selectLocation = coordinate;
        [blockSelf getNetData];
    };
    [self.navigationController pushViewController:mapVC animated:YES];
}
- (void)viewEndEditing {
    [self.searchBar resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    self.clearMaskView.hidden = NO;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    self.clearMaskView.hidden = YES;
}
static NSString *storesNearbyTableIdentifier = @"storesNearbyTableIdentifier";
- (void)createTableView {
    [self.tableView registerNib:[UINib nibWithNibName:@"StoresNearbyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:storesNearbyTableIdentifier];
    [self.tableView clearExtendCellLine];
}
- (void)updateRightButtonTitle:(NSString *)titleStr {
    [self.rightButton setTitle:titleStr forState:UIControlStateNormal];
}
#pragma mark - 网络请求
- (void)getLocation {
    //初始化BMKLocationService
    self.locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    self.annotation = [[BMKUserLocation alloc] init];
}
- (void)getLocationName:(CLLocationCoordinate2D)coordinate {
    __block typeof(self) blockSelf = self;
    [MYAFNetworking GETNormal:BASE_Baidu_Map parameters:@{@"location":[NSString stringWithFormat:@"%f,%f",coordinate.latitude,coordinate.longitude],@"pois":@"0",@"output":@"json",@"ak":BaiduWebKitKey} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        NSLog(@"%@",dic);
        if ([dic isKindOfClass:[NSDictionary class]]) {
            NSString *city = [[[dic safeJsonObjectForKey:@"result"] safeJsonObjectForKey:@"addressComponent"] safeJsonObjectForKey:@"city"];
            if (TextIsNotNil(city)) {
                [blockSelf updateRightButtonTitle:city];
            }
        } else {
            [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"获取定位失败" animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
        [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"获取定位失败" animated:YES];
    }];
}
- (void)getNetData {
    
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
    [parameter setObject:@(self.selectLocation.longitude) forKey:@"coordinatex"];
    [parameter setObject:@(self.selectLocation.latitude) forKey:@"coordinatey"];
    
    [parameter setObject:self.searchBar.text forKey:@"keyword"];
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MYAFNetworking POST:URL_Shop_Get parameters:parameter success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSArray *dataArr = responseObject[@"data"];
            
            [blockSelf.tableArray removeAllObjects];
            for (NSDictionary *dic in dataArr) {
                StoresNearbyHomeModel *model = [StoresNearbyHomeModel mj_objectWithKeyValues:dic];
                [blockSelf.tableArray addObject:model];
            }
            [blockSelf.tableView reloadData];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - 实现相关delegate 处理位置信息更新
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    if (_annotation.location.coordinate.latitude == 0 && _annotation.location.coordinate.longitude == 0) {
        _annotation = userLocation;
        [_locService stopUserLocationService];
        [self getLocationName:userLocation.location.coordinate];
        
        self.selectLocation = userLocation.location.coordinate;
        [self getNetData];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StoresNearbyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:storesNearbyTableIdentifier forIndexPath:indexPath];
    StoresNearbyHomeModel *model = self.tableArray[indexPath.row];
    
    [cell.storeImageView sd_setImageWithURL:GetUrl(model.simg) placeholderImage:PlaceholderImageSmall changeContentModel:UIViewContentModeScaleAspectFill];
    [cell.storeNameLabel setText:model.sname];
    [cell.storeDistanceLabel setText:[NSString stringWithFormat:@"距离：%@km",model.sdistance]];
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    StoresNearbyGoodsViewController *goodsVC = [[StoresNearbyGoodsViewController alloc] init];
    goodsVC.storeModel = self.tableArray[indexPath.row];
    [self.navigationController pushViewController:goodsVC animated:YES];
}
#pragma mark - DZNEmptyDataSetSource & DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"附近暂无店铺"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [self getNetData];
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self viewEndEditing];
    [self getNetData];
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
